package cn.gok.homework;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Book{
    private int bid;
    private String name;
    private float price;

    public Book(int bid, String name, float price) {
        this.bid = bid;
        this.name = name;
        this.price = price;
    }
    public void sell(){
        System.out.println(this.name+"被卖掉了！");
    }
    private void sell(float price,String name){
        System.out.println(this.name+"以"+price+"元卖给了"+name);
    }

    @Override
    public String toString() {
        return "Book{" +
                "bid=" + bid +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
public class Homework {
    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        作业();
    }

    private static void 作业() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //1 获取Book类信息，并获取全属性构造函数对象constructor
        Class c = Book.class;
        Constructor con = c.getDeclaredConstructor(int.class,String.class,float.class);
       // 2 利用该构造对象，创建1个书的实例。
        Book book = (Book) con.newInstance(10,"红楼梦",50f);
        System.out.println(book);
        //3 通过反射，分别获取两个sell方法对应的method对象，
        //并破坏封装性，分别调用该方法。
        //method.invoke(book,参数列表) ;//field.set(book,新值)  ,field.get(book)--旧值
        Method m1 = c.getDeclaredMethod("sell");
        m1.invoke(book);//执行无参的sell方法
        Method m2 = c.getDeclaredMethod("sell",float.class,String.class);
        m2.setAccessible(true); //破坏封装性
        m2.invoke(book,30f,"小白");//执行无参的sell方法     book.sell(30,小白 );
    }
}
